package com.xiaobaibai.security.login.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.common.response.ResponseCode;
import com.xiaobaibai.common.response.ResponseFormat;
import com.xiaobaibai.config.MyException;
import com.xiaobaibai.pojo.UserAdmin;
import com.xiaobaibai.units.TokenUnit;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录成功处理层,用于返回token
 */
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String authority=null;
        for (GrantedAuthority authenticationAuthority : authentication.getAuthorities()) {
            authority=authenticationAuthority.getAuthority();
        }
        UserAdmin userAdmin=new UserAdmin();
        userAdmin.setUserRole(authority);//获取身份
        userAdmin.setUserId(authentication.getName());//获取userId
        String token = TokenUnit.getToken(userAdmin);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        ResponseFormat<String> loginSuccess =
                ResponseFormat.createSuccessResponse("登录成功", token);
        writer.write(JSON.toJSONString(loginSuccess));
    }

}
